package com.yiqi.zhiyuan.feature.order.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.suozhang.framework.component.recyclerview.DividerItemDecoration;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.DensityUtil;
import com.suozhang.framework.widget.dialog.ActionSheetDialog;
import com.suozhang.framework.widget.dialog.NormalDialog;
import com.suozhang.framework.widget.dialog.OnBtnClickL;
import com.suozhang.framework.widget.dialog.OnOperItemClickL;
import com.yiqi.zhiyuan.R;
import com.yiqi.zhiyuan.common.lib.widget.FullyGridLayoutManager;
import com.yiqi.zhiyuan.entity.vo.ChangeReasonVO;
import com.yiqi.zhiyuan.entity.vo.OrderVO;
import com.yiqi.zhiyuan.feature.mine.view.adapter.GridImageAdapter;
import com.yiqi.zhiyuan.feature.order.contract.ChangeContract;
import com.yiqi.zhiyuan.feature.order.dependencies.change.ChangePresenterModule;
import com.yiqi.zhiyuan.feature.order.dependencies.change.DaggerChangeComponent;
import com.yiqi.zhiyuan.feature.order.view.adapter.ReasonAdapter;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ChangeOrderActivity extends BaseActivity implements OnOperItemClickL, GridImageAdapter.OnItemClickListener,
        GridImageAdapter.onAddPicClickListener, ChangeContract.View, TextWatcher {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.rv_change_reason)
    RecyclerView mRvChangeReason;
    @BindView(R.id.rv_add_image)
    RecyclerView mRvAddImage;
    @BindView(R.id.edt_change_reason_expain)
    EditText mEdtChangeReasonExpain;
    @BindView(R.id.edt_change_reason_count)
    TextView mTvChangeReasonCount;
    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter adapter;
    private int maxSelectNum = 4;
    private ActionSheetDialog dialog;
    private ReasonAdapter mReasonAdapter;
    List<String> strings = null;
    private OrderVO mOrderVO;

    private String mReasonId;

    @Inject
    ChangeContract.Presenter mPresenter;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_change_order;
    }

    @Override
    protected void initInjector() {
        DaggerChangeComponent.builder().changePresenterModule(new ChangePresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        initToolBar(mToolbar, "订单改派", true, true);
        initDialog();
        initImageAdapter();
        initAdapter();
    }

    @Override
    protected void initData() {
        mOrderVO = (OrderVO) this.getIntent().getSerializableExtra("order_info");
        mPresenter.selectChangeReason();
    }

    @Override
    protected void initEvent() {
        mEdtChangeReasonExpain.addTextChangedListener(this);
    }

    @OnClick(R.id.btn_order_service)
    public void onViewNoClicked() {
        finish();
    }

    @OnClick(R.id.btn_order_passengers)
    public void onViewSureClicked() {
        if (TextUtils.isEmpty(mReasonId)) {
            showErrorMsg("请选择改派原因");
            return;
        }
        initTipsDialog();
    }


    private void initDialog() {
        final String[] stringItems = {getString(R.string.common_photo_take_text), getString(R.string.common_photo_select_text)};
        dialog = new ActionSheetDialog(this, stringItems, null);
        dialog.isTitleShow(false);
        dialog.setOnOperItemClickL(this);
    }

    @Override
    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (dialog != null) dialog.dismiss();
        switch (position) {
            case 0:
                PictureSelector.create(this)
                        .openCamera(PictureMimeType.ofImage())
                        .theme(R.style.picture_default_style)
                        .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                        .previewImage(false)// 是否可预览图片
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .isCamera(true)
                        .maxSelectNum(maxSelectNum)
                        .enableCrop(false)// 是否裁剪
                        .compress(true)// 是否压缩
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                        .selectionMedia(selectList)// 是否传入已选图片
                        .scaleEnabled(true)
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;
            case 1:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .theme(R.style.picture_default_style)
                        .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                        .previewImage(false)// 是否可预览图片
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .isCamera(false)
                        .maxSelectNum(maxSelectNum)
                        .enableCrop(false)// 是否裁剪
                        .compress(true)// 是否压缩
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                        .selectionMedia(selectList)// 是否传入已选图片
                        .scaleEnabled(true)
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                break;
        }
    }

    private void initImageAdapter() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mRvAddImage.setLayoutManager(manager);
        mRvAddImage.setHasFixedSize(false);
        mRvAddImage.setNestedScrollingEnabled(true);
        adapter = new GridImageAdapter(this, this);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        mRvAddImage.setAdapter(adapter);
        adapter.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(int position, View v) {
        if (selectList.size() > 0) {
            LocalMedia media = selectList.get(position);
            String pictureType = media.getPictureType();
            int mediaType = PictureMimeType.pictureToVideo(pictureType);
            switch (mediaType) {
                case 1:
                    PictureSelector.create(this).themeStyle(R.style.picture_default_style).openExternalPreview(position, selectList);
                    break;
            }
        }
    }

    @Override
    public void onAddPicClick() {
        if (dialog != null) dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);

                    for (LocalMedia media : selectList) {
                        Log.i("-----》", media.getPath());
                    }
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    private void initAdapter() {
        mRvChangeReason.setLayoutManager(new LinearLayoutManager(this));
        mRvChangeReason.addItemDecoration(new DividerItemDecoration(DividerItemDecoration.VERTICAL).setHeight(DensityUtil.dp2px(1)));
        mReasonAdapter = new ReasonAdapter();
        mReasonAdapter.bindToRecyclerView(mRvChangeReason);
        mReasonAdapter.checkState(-1);
        mReasonAdapter.setOnItemClickListener(listener);


    }

    private BaseQuickAdapter.OnItemClickListener listener = new BaseQuickAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            mReasonAdapter.checkState(position);
            mReasonId = mReasonAdapter.getItem(position).getValue();
        }
    };

    private void initTipsDialog() {
        NormalDialog dialog = new NormalDialog(this);
        dialog.title(getString(R.string.dialog_order_change_title));
        dialog.content(getString(R.string.doalog_order_change));
        dialog.btnNum(2);
        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dialog.dismiss();
            }
        }, new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                dialog.dismiss();
                strings = new ArrayList<>();
                if (selectList != null && selectList.size() > 0) {
                    for (LocalMedia media : selectList) {
                        mPresenter.uploadImage(media.getCompressPath());
                    }
                } else {
                    mPresenter.changeOrder(
                            mOrderVO.getUseCarType(),
                            mOrderVO.getOrderNo(),
                            mReasonId,
                            mEdtChangeReasonExpain.getText().toString().trim(),
                            null);
                }
            }
        });
        dialog.show();

    }

    @Override
    public void showChangeReasonSuccess(List<ChangeReasonVO> data) {
        mReasonAdapter.setNewData(data);
    }

    @Override
    public void showChangeReasonError(String errorMsg) {
        showErrorMsg(errorMsg);
    }

    @Override
    public void showUploadImageSuccess(String imageUrl) {
        strings.add(imageUrl);
        if (strings.size() == selectList.size()) {
            mPresenter.changeOrder(
                    mOrderVO.getUseCarType(),
                    mOrderVO.getOrderNo(),
                    mReasonId,
                    mEdtChangeReasonExpain.getText().toString().trim(),
                    strings);
        }
    }

    @Override
    public void showUploadImageError(String errorMsg) {
        showErrorMsg(errorMsg);
    }

    @Override
    public void showChangeOrderSuccess() {
        finish();
    }

    @Override
    public void showChangeOrderError(String errorMsg) {
        showErrorMsg(errorMsg);
    }



    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        mTvChangeReasonCount.setText(String.format("%s/100",s.length()));
    }
}
